package com.ycg.biquge.schedule;

import cn.hutool.core.util.ObjectUtil;
import com.ycg.biquge.mapper.NovelMapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

import static com.ycg.biquge.constant.CacheConstant.CHAPTER_SCORE_KEY;
import static com.ycg.biquge.constant.CacheConstant.NOVEL_SCORE_KEY;

/**
 * @author YCG
 * @date 2024-05-12 19:01
 * @description 定时更新小说分值
 */
@Component("scoreSchedule")
public class ScoreSchedule {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private NovelMapper novelMapper;

    /**
     * 每30分钟执行一次
     */
    @Scheduled(cron = "0 0/30 * * * *")
    public void saveScore() {
        System.out.println("定时任务");
        // 定时从缓存中读取小说分值, 存储到数据库
        saveScoreByType(CHAPTER_SCORE_KEY,1);
        saveScoreByType(NOVEL_SCORE_KEY,2);

    }

    private void saveScoreByType(String type, Integer weight) {

        Long count = stringRedisTemplate.opsForList().size(type);
        if (ObjectUtil.isNotNull(count) && count > 0) {
            List<String> novelIds = stringRedisTemplate.opsForList().rightPop(type, count);
            assert novelIds != null;
            HashMap<Integer, Integer> map = new HashMap<>();
            List<Integer> ids = novelIds.stream().map(Integer::parseInt).toList();
            for (Integer id : ids) {
                if (map.containsKey(id)) {
                    map.put(id, map.get(id) + weight);
                } else {
                    map.put(id, weight);
                }
            }
            map.forEach((id, score) -> {
                novelMapper.saveScore(id, score);
            });
            System.out.println(map);
        }
    }
}
